#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
  int fpin, fpout;
  off_t res;
  off_t filesize;
  int Hsize;
  int Hsizetotal;
  int Vsize;
  int Vsizetotal;
  char current_byte = 0;
  int i,j;

  if(argc < 7)
  {
    printf("please use %s Hsize Hsizetotal Vsize Vsizetotal inputfile.gray outputfile.gray\n", argv[0]);
    return 1;
  }
  Hsize      = atoi(argv[1]);
  Hsizetotal = atoi(argv[2]);
  Vsize      = atoi(argv[3]);
  Vsizetotal = atoi(argv[4]);

  fpin = open(argv[5], O_RDONLY);
  if(fpin < 0)
  {
    printf("input file %s could not be opened\n", argv[5]);
    return 2;
  }
  fpout = open(argv[6], O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);
  if(fpout < 0)
  {
    printf("output file %s could not be opened\n", argv[6]);
    return 2;
  }
  filesize = lseek(fpin, 0L, SEEK_END);
  if(filesize < 0)
  {
    perror("fseek1");
    return 3;
  }
  res = lseek(fpin, (off_t)0, SEEK_SET);
  if(res < 0)
  {
    perror("fseek2");
    return 4;
  }

  printf("inputfile has %0ld bytes, expected size %0d\n", filesize, Hsize*Vsize);
  for(i=0;i<Hsizetotal;i++)
  {
    for(j=0;j<Vsizetotal;j++)
    {
      if((i<Hsize)&&(j<Vsize))
      {
        if(read(fpin, &current_byte, 1)<0)
        {
          perror("read");
          return 5;
        }
      }
      if(write(fpout, &current_byte, 1)<0)
      {
        perror("write");
        return 5;
      }
    }
  }
  close(fpin);
  close(fpout);
  return 0;
}
